import { ipcMain, BrowserWindow } from 'electron';
import { ChatManager } from '../core/chat';
import { ElectronStreamHandler } from './electron-stream-handler';
import { configManager } from '../utils/config';
import { HistorySaver } from '../ui/history-saver';

export class ElectronChatBridge {
  private chatManager: ChatManager;
  private mainWindow: BrowserWindow;
  private historySaver: HistorySaver;

  constructor(mainWindow: BrowserWindow) {
    this.mainWindow = mainWindow;
    
    // 创建历史保存器
    this.historySaver = new HistorySaver(true);
    
    // 创建Electron专用的流处理器
    const streamHandler = new ElectronStreamHandler(mainWindow);
    
    // 传入历史保存器到ChatManager
    this.chatManager = new ChatManager(streamHandler, this.historySaver);
    
    // 从配置连接 MCP 服务器
    this.connectMCPServers();
    
    this.setupIpcHandlers();
  }

  private setupIpcHandlers() {
    // AI聊天IPC处理器
    ipcMain.handle('ai-chat', async (event, message: string) => {
      try {
        console.log('🚀 桥接: 收到AI聊天请求:', message);
        console.log('🔍 桥接: ChatManager状态检查', {
          chatManagerExists: !!this.chatManager,
          chatManagerType: typeof this.chatManager,
          sendMessageExists: !!(this.chatManager?.sendMessage)
        });
        
        // 直接调用原有的ChatManager方法
        console.log('📤 桥接: 调用 ChatManager.sendMessage');
        await this.chatManager.sendMessage(message);
        console.log('✅ 桥接: ChatManager.sendMessage 执行成功');
        
        return { success: true };
      } catch (error) {
        console.error('❌ 桥接: AI聊天错误:', error);
        console.error('📝 桥接: 错误详情:', {
          message: error instanceof Error ? error.message : '未知错误',
          stack: error instanceof Error ? error.stack : '无堆栈信息',
          name: error instanceof Error ? error.name : '未知错误类型'
        });
        
        this.mainWindow.webContents.send('ai-error', { 
          error: error instanceof Error ? error.message : '聊天失败' 
        });
        return { success: false, error: error instanceof Error ? error.message : '聊天失败' };
      }
    });

    // 获取聊天历史
    ipcMain.handle('get-chat-history', async () => {
      try {
        // 使用原有的ChatManager方法
        const messages = this.chatManager.getHistoryManager().getMessages();
        return { success: true, messages };
      } catch (error) {
        return { success: false, error: error instanceof Error ? error.message : '获取历史失败' };
      }
    });

    // 清空聊天历史
    ipcMain.handle('clear-chat-history', async () => {
      try {
        // 使用原有的ChatManager方法
        this.chatManager.clearHistory();
        return { success: true };
      } catch (error) {
        return { success: false, error: error instanceof Error ? error.message : '清空历史失败' };
      }
    });

    // 获取提示词列表
    ipcMain.handle('get-prompts', async () => {
      try {
        const prompts = this.chatManager.getAllPrompts();
        const current = this.chatManager.getCurrentPrompt();
        return { success: true, prompts, current };
      } catch (error) {
        return { success: false, error: error instanceof Error ? error.message : '获取提示词失败' };
      }
    });

    // 切换提示词
    ipcMain.handle('switch-prompt', async (event, index: number) => {
      try {
        this.chatManager.changePrinciple(index);
        const current = this.chatManager.getCurrentPrompt();
        return { success: true, current };
      } catch (error) {
        return { success: false, error: error instanceof Error ? error.message : '切换提示词失败' };
      }
    });

    // 取消当前请求
    ipcMain.handle('abort-chat', async () => {
      try {
        this.chatManager.abort();
        return { success: true };
      } catch (error) {
        return { success: false, error: error instanceof Error ? error.message : '取消请求失败' };
      }
    });

    // 获取历史会话列表（从文件系统）
    ipcMain.handle('get-history-list', async () => {
      try {
        const historyList = this.historySaver.getHistoryList();
        console.log('🔍 桥接: 获取历史会话列表成功', {
          sessionCount: historyList.length,
          sessions: historyList.map(s => ({ sessionId: s.sessionId, title: s.title }))
        });
        return historyList;
      } catch (error) {
        console.error('❌ 桥接: 获取历史会话列表失败:', error);
        throw error;
      }
    });

    // 加载特定会话到当前聊天
    ipcMain.handle('load-session-to-chat', async (event, sessionId: string) => {
      try {
        console.log('🔄 桥接: 开始加载会话:', sessionId);
        
        // 从文件系统加载历史数据
        const historyData = this.historySaver.loadHistoryBySessionId(sessionId);
        if (!historyData) {
          throw new Error(`未找到会话: ${sessionId}`);
        }
        
        // 加载到当前聊天管理器
        this.chatManager.loadSessionFromHistory(historyData.messages);
        
        console.log('✅ 桥接: 会话加载成功', {
          sessionId: historyData.sessionId,
          messageCount: historyData.messages.length
        });
        
        return { success: true, sessionId, messageCount: historyData.messages.length };
      } catch (error) {
        console.error('❌ 桥接: 加载会话失败:', error);
        throw error;
      }
      });

    }


  // 从配置连接 MCP 服务器
  private async connectMCPServers() {
    const enabledServers = configManager.getEnabledMCPServers();
    
    if (enabledServers.length === 0) {
      console.log('📡 未配置启用的 MCP 服务器');
      return;
    }

    console.log(`📡 正在连接 ${enabledServers.length} 个 MCP 服务器...`);
    
    for (const server of enabledServers) {
      try {
        console.log(`🔗 连接到 ${server.name}...`);
        const success = await this.chatManager.connectMCPServer(
          server.name, 
          server.command, 
          server.cwd
        );
        
        if (success) {
          console.log(`✅ ${server.name} 连接成功`);
        } else {
          console.log(`❌ ${server.name} 连接失败`);
        }
      } catch (error) {
        console.error(`❌ ${server.name} 连接错误:`, error);
      }
    }
  }

  // 获取ChatManager实例（如果需要直接访问）
  getChatManager(): ChatManager {
    return this.chatManager;
  }
}